package kr.hkit.androidcomplete02.XMLparser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import kr.hkit.androidcomplete02.R;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class Dom_parserAcitivity extends Activity {
	
	private ListView list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		
		new ParsingXML().execute("order.xml");
		
	}
	
	private class ParsingXML extends AsyncTask<String, Void, ArrayList<Item>> {
		private ProgressDialog progressDlg;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDlg = ProgressDialog.show(Dom_parserAcitivity.this, "Wait", "xml parsing...");
		}
		
		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			super.onPostExecute(result);
			MyAdapter adapter = new MyAdapter(Dom_parserAcitivity.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
			
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str=br.readLine())!=null){
					sb.append(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}

		//DOM parser는 이부분
		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arItem = new ArrayList<Item>();
			Item itemClass;
			
			try {
				InputStream iStream = new ByteArrayInputStream(xml.getBytes("utf-8"));

				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document dc = builder.parse(iStream); //읽은문서에서 트리만듬
				//트리에서 최상위 노드 찾고. 
				Element order = dc.getDocumentElement();
				NodeList items = order.getElementsByTagName("item"); //태그명으로 노드리스트 불러오겟다
				
				for(int i =0; i<items.getLength(); i++) {
					itemClass = new Item();
					Node itemNode = items.item(i);
					//노드는 한줄 가져온거
					Node itemValue= itemNode.getFirstChild(); //마우스
					itemClass.setItemName(itemValue.getNodeValue());
					
					//속성값을 가지고 있냐? price랑 maker같은 속성
					if(itemNode.hasAttributes()){ //가지고 있다면 불러와야지
						NamedNodeMap attrs= itemNode.getAttributes();
						//메이컨지 프라이슨지 구분해야함. 이게 노드네임
						for (int j=0; j<attrs.getLength(); j++) {
							 Node attr = attrs.item(j); //하나의 속성가져옴
							 if(attr.getNodeName().equalsIgnoreCase("price")){
								 itemClass.setItemPrice(Integer.parseInt(attr.getNodeValue()));
							 }else{
								 itemClass.setMakerName(attr.getNodeValue());
							 }
						}
					}
					arItem.add(itemClass);
				}
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return arItem;
		}
	}
}
